package com.example.fengyungo.activity.main;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.example.fengyungo.R;
import com.example.fengyungo.activity.BaseActivity;
import com.example.fengyungo.activity.message.ChatActivity;
import com.example.fengyungo.constant.DriverConstant;
import com.example.fengyungo.constant.MessageConstant;
import com.example.fengyungo.constant.OrderConstant;
import com.example.fengyungo.constant.ResultConstant;
import com.example.fengyungo.constant.UserConstant;
import com.example.fengyungo.domain.Driver;
import com.example.fengyungo.domain.User;
import com.example.fengyungo.utils.BitmapUtils;
import com.example.fengyungo.utils.OkHttpUtils;
import com.example.fengyungo.utils.SharedPreferencesUtils;
import com.example.fengyungo.utils.ThreadPoolUtil;

import java.io.IOException;

/**
 * 订单发布着的用户详情
 */
public class OrderUserActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "OrderUserActivity";

    /**
     * 发货者id，用户id
     */
    String userId;
    /**
     * 返回
     */
    ImageButton back;
    /**
     * 发送消息
     */
    Button chat;
    /**
     * 用户昵称
     */
    String userNickname;
    /**
     * 用户性别
     */
    String userSex;
    /**
     * 用户电话号码
     */
    String userPhone;
    /**
     * 用户邮箱
     */
    String userMail;
    /**
     * 用户头像
     */
    String userAvatar;
    /**
     * 昵称
     */
    TextView nicknameTextView;
    /**
     * 电话号码
     */
    TextView phoneTextView;
    /**
     * 邮箱
     */
    TextView mailTextView;
    /**
     * 性别
     */
    TextView sexTextView;
    /**
     * 头像
     */
    ImageView avatarImageView;
    /**
     * 用户
     */
    User user;
    /**
     * 司机
     */
    Driver driver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_user);

        driver = SharedPreferencesUtils.getDriverInfo(this);

        // 用户id
        Intent intent = getIntent();
        userId = intent.getStringExtra(OrderConstant.USER_ID);

        // 返回
        back = findViewById(R.id.back);
        back.setOnClickListener(this);

        // 发消息
        chat = findViewById(R.id.chat_button);
        chat.setOnClickListener(this);

        initControl();

        // 获取用户信息
        User user = getUserInfo();
        Log.d(TAG, "onCreate: userNickname=" + userNickname);
        Log.d(TAG, "onCreate: user=" + user);

        // 将用户信息填入
        nicknameTextView.setText(user.getUserNickname());
        phoneTextView.setText(user.getUserPhone());
        sexTextView.setText(user.getUserSex());
        mailTextView.setText(user.getUserMail());
        // 设置头像
        Bitmap bitmapFromSp = BitmapUtils.getBitmapFromSharedPreferences(this, userId);
        BitmapDrawable avatarDrawable = new BitmapDrawable(getResources(), bitmapFromSp);
        Log.d(TAG, "onCreate: bitmapFromSp=" + bitmapFromSp);
        Log.d(TAG, "onCreate: userAvatar=" + userAvatar);
        avatarImageView.setBackground(avatarDrawable);
    }

    private void initControl() {
        nicknameTextView = findViewById(R.id.nickname);
        phoneTextView = findViewById(R.id.phone);
        sexTextView = findViewById(R.id.sex);
        avatarImageView = findViewById(R.id.avatar);
        mailTextView = findViewById(R.id.mail);
    }

    /**
     * 点击事件
     *
     * @param view View
     */
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.chat_button:
                Intent intent = new Intent(this, ChatActivity.class);
                intent.putExtra(MessageConstant.USER_ID, userId);
                intent.putExtra(MessageConstant.USER_NICKNAME, userNickname);
                startActivity(intent);
                // 更新消息界面的列表
                addMessageList();
                break;
            default:
                break;
        }
    }

    /**
     * 获取用户信息
     */
    private User getUserInfo() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    // 发送GET请求到后端，并接收响应数据
                    String url = DriverConstant.URL_USER_DRIVER + "/getUserById/" + userId;
                    String responseData = OkHttpUtils.get(url);
                    JSONObject jsonObject = JSONObject.parseObject(responseData);
                    int code = jsonObject.getInteger(ResultConstant.CODE);
                    String msg = jsonObject.getString(ResultConstant.MSG);
                    Log.d(TAG, "run: code=" + code);
                    if (code == ResultConstant.SUCCESS) {
                        JSONObject json = jsonObject.getJSONObject(ResultConstant.DATA);
                        userNickname = json.getString(UserConstant.USER_NICKNAME);
                        userMail = json.getString(UserConstant.USER_MAIL);
                        userPhone = json.getString(UserConstant.USER_PHONE);
                        userSex = json.getString(UserConstant.USER_SEX);
                        userAvatar = json.getString(UserConstant.USER_AVATAR);
                        Log.d(TAG, "run: userNickname=" + userNickname);
                        user = new User();
                        user.setUserNickname(userNickname);
                        user.setUserMail(userMail);
                        user.setUserPhone(userPhone);
                        user.setUserSex(userSex);
                        user.setUserAvatar(userAvatar);
                        Log.d(TAG, "run: user=" + user);
                    } else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(OrderUserActivity.this, msg, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(OrderUserActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        };
        ThreadPoolUtil.execute(runnable);
        while (user == null) {
        }
        return user;
    }

    /**
     * 更新消息界面的列表
     */
    private void addMessageList() {
        Runnable runnable = () -> {
            try {
                String url = MessageConstant.URL + "/addMessageList/" + driver.getId() + "/" + userId;
                String responseData = OkHttpUtils.post(url, "");
                Log.d(TAG, "addMessageList: responseData=" + responseData);
                JSONObject jsonObject = JSONObject.parseObject(responseData);
                int code = jsonObject.getInteger(ResultConstant.CODE);
                String msg = jsonObject.getString(ResultConstant.MSG);
                if (code == ResultConstant.SUCCESS) {
                    Log.d(TAG, "addMessageList: success");
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(OrderUserActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(OrderUserActivity.this, getString(R.string.connection_error), Toast.LENGTH_SHORT).show();
                    }
                });
            }
        };
        ThreadPoolUtil.execute(runnable);
    }
}